/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.lizg.Model;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ProgressMonitor;
import javax.swing.ProgressMonitorInputStream;

/**
 *
 * @author LizG
 */
public class Send {

    private Socket socket;
    private BufferedOutputStream bos;
    private int len;
    private static String ip = null;
    private static String file = null;
    private ProgressMonitorInputStream monitor;
    public Send() {
    }

    public Send(String ip) {
        this.ip = ip;
    }

    //get_set_
    public void setFile(String file) {
        Send.file = file;
    }

    public static void setIp(String ip) {
        Send.ip = ip;
    }
    
    public void send() {
        try {
            System.out.println("正在发送文件。。。");
            System.out.println("send的ip:" + ip);
            socket = new Socket(ip, 8089);
            monitor = new ProgressMonitorInputStream(null, "进度", 
                                                new BufferedInputStream(new FileInputStream(file)));
            //封装文件到输入流中
            System.out.println("封装文件到输入流中完成");
            //封装通道中的流
            //把文件中的流传入通道中   文件--->InStream---->OutStream(通道)
            bos = new BufferedOutputStream(socket.getOutputStream());
            System.out.println("封装通道中的流完成");
            //System.out.println("……");
            ProgressMonitor progressMonitor = monitor.getProgressMonitor();
            byte[] bys = new byte[2048];
            len = 0;
            int all = monitor.available();
            int readed = 0;
            float process = 0;
            while ((len = monitor.read(bys)) != -1) {
                readed+=len;
                bos.write(bys, 0, len);
                bos.flush();
                if((process = (float)(readed/all)) != 0){
                progressMonitor.setNote("已完成:" + String.format("%.2f", process) + "%");
                }
            }
            socket.shutdownOutput();
            //释法
            bos.close();
            monitor.close();
        } catch (IOException ex) {
            Logger.getLogger(Send.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
